package com.example.zbh.dsliao.ui.activty;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.zbh.dsliao.MusicIdle;
import com.example.zbh.dsliao.R;
import com.example.zbh.dsliao.constant.Constant;
import com.example.zbh.dsliao.model.entity.MusicMessage;
import com.example.zbh.dsliao.model.entity.SearchSongList;
import com.example.zbh.dsliao.presenter.Music_Detail_Presenter;
import com.example.zbh.dsliao.ui.viewinterface.ShowDownLoaderResultListener;
import com.example.zbh.dsliao.utils.FormatTime;
import com.example.zbh.dsliao.utils.MyEventBus;

import java.util.List;

import de.greenrobot.event.EventBus;


public class Music_Detail_Activity extends MVPBaseActivity<ShowDownLoaderResultListener,Music_Detail_Presenter> implements View.OnClickListener, SeekBar.OnSeekBarChangeListener, ShowDownLoaderResultListener {
    private ImageView img_pull_down, img_download, img_collect, img_mode, img_previous, img_play, img_pause, img_next, img_select;
    private TextView tv_music_Album, tv_songs, tv_player_progress, tv_player_max;
    private SeekBar seekBar;
    private List<SearchSongList> songList;


    private int currentIndex;


    //定义一个播放的接口操作对象
    private MusicIdle musicIdle;
    //定义一个远程服务连接对象
    private ServiceConnection coon = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //初始化操作对象
            musicIdle = MusicIdle.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    //广播
    private  MyBroadcastReceiver myBroadcastReceiver;


    //获得值
    private int zeroId;         //0位置的id
    private int oneId;
    private int position;




    @Override
    protected Music_Detail_Presenter createPresenter() {
        return new Music_Detail_Presenter(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(coon);
        unregisterReceiver(myBroadcastReceiver);
        EventBus.getDefault().unregister(this);
    }

    public void onEvent(MyEventBus.CurrentIndex currentIndex) {
        Log.d("SongListActivity", "currentIndex:" + currentIndex);
        seekBar.setProgress(currentIndex.getCurrentIndex());
        tv_player_progress.setText(FormatTime.formatTime((long) currentIndex.getCurrentIndex()));
    }

    public void onEvent(MyEventBus.MaxProgress maxProgress) {
        Log.d("SongListActivity", "currentIndex:" + maxProgress);
        seekBar.setMax(maxProgress.getMaxProgress());
        tv_player_max.setText(songList.get(position % songList.size()).getAudition_list().get(0).getDuration());

    }

    @Override
    protected int getLayOut() {
        return R.layout.activity_music_detail;
    }

    @Override
    protected void initView() {
        tv_music_Album = (TextView) findViewById(R.id.tv_music_Album);  //专辑名
        tv_songs = (TextView) findViewById(R.id.tv_songs);              //歌
        tv_player_progress = (TextView) findViewById(R.id.tv_player_progress);     //当前进度
        tv_player_max = (TextView) findViewById(R.id.tv_player_max);    //最大进度
        seekBar = (SeekBar) findViewById(R.id.seekBar);                 //拖动条
        img_pull_down = (ImageView) findViewById(R.id.img_pull_down);   //下拉关闭
        img_download = (ImageView) findViewById(R.id.img_download);     //下载
        img_collect = (ImageView) findViewById(R.id.img_collect);       //收藏
        img_mode = (ImageView) findViewById(R.id.img_mode);             //播放模式
        img_previous = (ImageView) findViewById(R.id.img_previous);     //上一首
        img_play = (ImageView) findViewById(R.id.img_play);             //播放
        img_pause = (ImageView) findViewById(R.id.img_pause);           //暂停
        img_next = (ImageView) findViewById(R.id.img_next);             //下一首
        img_select = (ImageView) findViewById(R.id.img_select);         //选择
    }


    @Override
    protected void initData() {

        //注册
        EventBus.getDefault().register(this);
        //绑定服务
        Intent intent = new Intent("com.lanou.service.player");
        bindService(intent, coon, BIND_AUTO_CREATE);

        //自定义广播
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.lanou.player.next");
        filter.addAction("com.lanou.player.previous");
        myBroadcastReceiver = new MyBroadcastReceiver();
        registerReceiver(myBroadcastReceiver, filter);


        click();
        getData();

    }



    /**
     * 监听事件
     * **/
    private void click() {
        img_pull_down.setOnClickListener(this);
        img_download.setOnClickListener(this);
        img_collect.setOnClickListener(this);
        img_mode.setOnClickListener(this);
        img_previous.setOnClickListener(this);
        img_play.setOnClickListener(this);
        img_pause.setOnClickListener(this);
        img_next.setOnClickListener(this);
        img_select.setOnClickListener(this);

        seekBar.setOnSeekBarChangeListener(this);
    }


    /**
     * 获得值
     * **/
    private void getData() {
        zeroId = getIntent().getIntExtra("zeroId", -1);
        oneId = getIntent().getIntExtra("oneId", -1);
        position = getIntent().getIntExtra("position", -1);
        MusicMessage musicMessage = new MusicMessage();
        musicMessage.setZeroId(zeroId);
        musicMessage.setOneId(oneId);
        musicMessage.setPosition(position);
        createPresenter().receiveMusicMessage(getUrl());
    }
    public String getUrl(){
        return Constant.MUSICDETAILFRONTURL +
                zeroId + Constant.MUSICDETAILMIDDLEURL +oneId + Constant.MUSICDETAILLATEURL;
    }



    /**
     * 监听
     * **/
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.img_pull_down:  //下拉关闭
                finish();
                overridePendingTransition(R.animator.pull_dowm_img_second, R.animator.pull_down_img_first);
                break;
            case R.id.img_download:   //下载
                break;
            case R.id.img_collect:    //收藏
                break;
            case R.id.img_mode:       //播放模式
                break;
            case R.id.img_previous:   //上一首

                break;
            case R.id.img_play:       //播放
                play();
                break;
            case R.id.img_pause:      //暂停
               pause();
                break;
            case R.id.img_next:       //下一首
               next();
                break;
            case R.id.img_select:     //选择
                break;
        }

    }

    private void next() {
        if(musicIdle != null){
            try {
                musicIdle.next();
                tv_music_Album.setText(songList.get(currentIndex % songList.size()).getAlbum_name());
                tv_songs.setText(songList.get(currentIndex % songList.size()).getSong_name() + "     《"
                        + songList.get(currentIndex % songList.size()).getSinger_name() + " 》");


                Log.i("zenmehuishi", songList.get(position% songList.size()).getAlbum_name());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    private void pause() {
        if (musicIdle != null) {
            try {
                musicIdle.pause();
                img_pause.setVisibility(View.GONE);
                img_play.setVisibility(View.VISIBLE);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    private void play() {
        if(musicIdle != null){
            try {
                musicIdle.setUrl(songList.get(position % songList.size()).getAudition_list().get(0).getUrl());
                img_play.setVisibility(View.GONE);
                img_pause.setVisibility(View.VISIBLE);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if(musicIdle != null){
            try {
                musicIdle.setProgress(seekBar.getProgress());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    //得到解析后的数据
    @Override
    public void showResult(List list) {
        SearchSongList searchSongList = (SearchSongList) list.get(position);
        songList = list;
        tv_music_Album.setText("专辑名:" + searchSongList.getAlbum_name());
        tv_songs.setText(searchSongList.getSong_name() + "          " +
                "《" + searchSongList.getSinger_name() + "》");
        tv_player_max.setText(searchSongList.getAudition_list().get(0).getDuration());

    }

    @Override
    public void showOtherResult(List list) {

    }


    //自定义广播
    class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("com.lanou.player.next")){
                if(musicIdle != null){
                position ++;
                } else if(intent.getAction().equals("com.lanou.player.previous")){
                    if(musicIdle != null){
                        position --;
                    }
                }
                img_play.setVisibility(View.GONE);
                img_pause.setVisibility(View.VISIBLE);
                String url = songList.get(position % songList.size()).getAudition_list().get(0).getUrl();
                if(musicIdle != null){
                    try {
                        musicIdle.setUrl(url);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }
}
